home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / benchmarks / cswitch / cswitch.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-08-31  |  2.1 KB  |  81 lines

  1. /* 
  2.  * cswitch.c --
  3.  *
  4.  *    Simple program to test context switching by sending short
  5.  *    messages back and forth through a pipe.  Invocation:
  6.  *    
  7.  *    cswitch count
  8.  *
  9.  *    Count tells how many times a one-byte message should be sent
  10.  *    back and forth between two processes.
  11.  *
  12.  * Copyright 1987, 1989 Regents of the University of California
  13.  * Permission to use, copy, modify, and distribute this
  14.  * software and its documentation for any purpose and without
  15.  * fee is hereby granted, provided that the above copyright
  16.  * notice appear in all copies.  The University of California
  17.  * makes no representations about the suitability of this
  18.  * software for any purpose.  It is provided "as is" without
  19.  * express or implied warranty.
  20.  */
  21.  
  22. #ifndef lint
  23. static char rcsid[] = "$Header: /sprite/src/benchmarks/cswitch/RCS/cswitch.c,v 1.1 89/08/31 13:19:37 ouster Exp $ SPRITE (Berkeley)";
  24. #endif not lint
  25.  
  26. #include <stdio.h>
  27. #include <sys/time.h>
  28.  
  29. main(argc,argv)
  30.     int argc;
  31.     char **argv;
  32. {
  33.     int count, i, toSlave[2], fromSlave[2];
  34.     int pid;
  35.     char buffer[10];
  36.     struct timeval begin ,end;
  37.     int micros;
  38.     double timePer;
  39.     extern int errno;
  40.  
  41.     if (argc != 2 ) {
  42.     fprintf(stderr, "Ping takes one argument: count.\n");
  43.     return;
  44.     }
  45.     count = 0;
  46.     sscanf(argv[1], "%d", &count);
  47.     pipe(toSlave);
  48.     pipe(fromSlave);
  49.     pid = fork();
  50.     if (pid == 0) {
  51.     write(fromSlave[1], "a", 1);
  52.     while (1) {
  53.         read(toSlave[0], buffer, 1);
  54.         if (buffer[0] != 'a') {
  55.         exit(0);
  56.         }
  57.         write(fromSlave[1], "a", 1);
  58.     }
  59.     }
  60.     if (pid == -1) {
  61.     fprintf(stderr, "Couldn't fork slave process: error %d.\n",
  62.         errno);
  63.     return;
  64.     }
  65.     read(fromSlave[0], buffer, 1);
  66.     gettimeofday(&begin, (struct timezone *) NULL);
  67.     for (i = 0; i < count; i++) {
  68.     write(toSlave[1], "a", 1);
  69.     read(fromSlave[0], buffer, 1);
  70.     }
  71.     gettimeofday(&end, (struct timezone *) NULL);
  72.     micros = 1000000*(end.tv_sec - begin.tv_sec)
  73.         + end.tv_usec - begin.tv_usec;
  74.     write(toSlave[1], "b", 1);
  75.     timePer = micros;
  76.     timePer /= count * 1000;
  77.  
  78.     printf("Elapsed time per ping (2 context switches): %.2f milliseconds.\n",
  79.         timePer);
  80. }
  81.